package com.by.controller;


import com.by.entity.AttrGroup;
import com.by.result.Result;
import com.by.service.AttrGroupService;
import com.by.vo.AttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/attr-group")
public class AttrGroupController {


    @Autowired
    private AttrGroupService attrGroupService;
    /**
     * 查询属性分组列表
     * @return 属性分组列表
     */
     @GetMapping("/list")
     public Result<List<AttrGroupVo>> listAttrGroup() {
         List<AttrGroup> list = attrGroupService.list();
         //转换为vo
         List<AttrGroupVo> attrGroupVoList = list.stream().map(item -> new AttrGroupVo(item.getAttrGroupId(),
                 item.getCatId(), item.getName(), item.getSort())).collect(Collectors.toList());
         return Result.success(attrGroupVoList);
     }

    /**
     * 添加属性分组
     * @param attrGroupVo 属性分组信息
     * @return 属性分组ID
     */
     @PostMapping("/save")
     public Result<Long> saveAttrGroup(@RequestBody AttrGroupVo attrGroupVo) {
         AttrGroup attrGroup = new AttrGroup();
         BeanUtils.copyProperties(attrGroupVo, attrGroup);
         attrGroupService.saveOrUpdate(attrGroup);
         return Result.success(attrGroup.getAttrGroupId());
     }

    /**
     * 删除属性分组
     * @param attrGroupId 属性分组ID
     * @return 是否删除成功
     */
     @DeleteMapping("/delete")
     public Result deleteAttrGroup(@RequestParam("attrGroupId") Long attrGroupId) {
         //校验属性分组是否存在
         AttrGroup attrGroup = attrGroupService.getById(attrGroupId);
         if (attrGroup == null) {
             return Result.error(400, "属性分组不存在");
         }
         //TODO 检查该属性分组是否关联了规格项
         //删除属性分组
         boolean b = attrGroupService.removeById(attrGroupId);
         return Result.success(b);
     }

    /**
     * 更新属性分组
     * @param attrGroupVo 属性分组信息
     * @return 属性分组ID
     */
     @PutMapping("/update")
     public Result updateAttrGroup(@RequestBody AttrGroupVo attrGroupVo) {
        //判断属性分组是否存在
         AttrGroup attrGroup = attrGroupService.getById(attrGroupVo.getAttrGroupId());
         if (attrGroup == null) {
             return Result.error(400, "属性分组不存在");
         }
         BeanUtils.copyProperties(attrGroupVo, attrGroup);
         return Result.success(attrGroupService.saveOrUpdate(attrGroup));
     }

}
